<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Env } from '../entity'
import type { Server } from '@renderer/server/entity'
import * as envApi from '../api/env'

const props = defineProps<{
  projectId: string
}>()

// 环境列表
const envList = ref<Env[]>([])

// 服务器列表
const serverList = ref<Server[]>([])

// 环境表单
const envDialogVisible = ref(false)
const envForm = ref<Partial<Env>>({})

// 加载环境列表
const loadEnvs = async () => {
  try {
    envList.value = await envApi.getProjectEnvs(props.projectId)
  } catch (error) {
    console.error('加载环境列表失败:', error)
    ElMessage.error('加载环境列表失败')
  }
}

// 环境相关操作
const handleAddEnv = () => {
  envForm.value = {}
  envDialogVisible.value = true
}

const handleEditEnv = (env: Env) => {
  envForm.value = { ...env }
  envDialogVisible.value = true
}

const handleDeleteEnv = async (env: Env) => {
  try {
    await ElMessageBox.confirm('确认删除该环境配置吗？', '提示', {
      type: 'warning'
    })
    await envApi.removeEnv(env.id)
    ElMessage.success('删除成功')
    loadEnvs()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleEnvSubmit = async () => {
  try {
    if (!envForm.value.name || !envForm.value.serverId || !envForm.value.serverPath) {
      ElMessage.warning('请填写必填项')
      return
    }

    if (envForm.value.id) {
      await envApi.updateEnv({
        id: envForm.value.id,
        name: envForm.value.name,
        serverId: envForm.value.serverId,
        serverPath: envForm.value.serverPath
      })
    } else {
      await envApi.addEnv(props.projectId, {
        name: envForm.value.name,
        serverId: envForm.value.serverId,
        serverPath: envForm.value.serverPath
      })
    }

    ElMessage.success('保存成功')
    envDialogVisible.value = false
    loadEnvs()
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 暴露方法给父组件
defineExpose({
  loadEnvs
})
</script>

<template>
  <div class="env-config">
    <div class="mb-4">
      <el-button type="primary" @click="handleAddEnv">添加环境</el-button>
    </div>

    <el-table :data="envList" border>
      <el-table-column label="环境名称" prop="name" />
      <el-table-column label="服务器" prop="serverName" />
      <el-table-column label="服务器路径" prop="serverPath" show-overflow-tooltip />
      <el-table-column label="操作" width="150">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleEditEnv(row)">编辑</el-button>
          <el-button link type="danger" @click="handleDeleteEnv(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 环境配置对话框 -->
    <el-dialog
      v-model="envDialogVisible"
      :title="envForm.id ? '编辑环境' : '新增环境'"
      width="500px"
      destroy-on-close
    >
      <el-form :model="envForm" label-width="100px">
        <el-form-item label="环境名称" required>
          <el-input v-model="envForm.name" placeholder="请输入环境名称" />
        </el-form-item>
        <el-form-item label="服务器" required>
          <el-select v-model="envForm.serverId" placeholder="请选择服务器">
            <el-option
              v-for="server in serverList"
              :key="server.id"
              :label="server.name"
              :value="server.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="服务器路径" required>
          <el-input v-model="envForm.serverPath" placeholder="请输入服务器路径" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="envDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEnvSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.mb-4 {
  margin-bottom: 16px;
}
</style> 